#!/usr/bin/python
# -*- coding: UTF-8 -*-

from flask import Flask, request
from gevent import pywsgi
from flask import render_template #渲染
import time
import threading
from login import yhlogin
from PJ import getpjlist,start,log

#pip install requests==2.29.0 -i https://pypi.tuna.tsinghua.edu.cn/simple/

app = Flask(__name__, static_url_path=None, static_folder='static')
app.config['JSON_AS_ASCII'] = False  # 解决中文乱码问题
user = []

@app.route("/",methods=["GET"])
def index():
    return render_template('index.html') #把index.html文件读进来，再交给浏览器

@app.route("/gettoken",methods=["POST"])
def gettoken():
    try:
        userNo = request.values.get("userNo")
        pwd = request.values.get("pwd")
    except:
        return "参数错误！"
    
    token = yhlogin(userNo,pwd)
    if(token == ""):
        return "网络错误或是账号密码不对！"
    else:
        if userNo not in user:
            user.append(userNo)
            timer = threading.Timer(1, task, args=(token,userNo,))
            timer.start()
        else:
            return "任务已存在，请勿重复添加！没有完成请稍候再重新添加！"
        return "任务添加成功，请等待10分钟后查看结果！"


def task(token,userNo):
    try:
        pjlist = getpjlist(token,userNo)
        for i in range(len(pjlist)):
            courseinfo = pjlist[i]
            start(token,userNo,courseinfo)
            time.sleep(3)
        user_ok = True
    except Exception as e:
        log(f"出错了{userNo}:{e}")
        user_ok = False
    finally:
        if user_ok:
            user.remove(userNo)
            log(f"{userNo}运行完成")
        else:
            timer = threading.Thread(target= task, args=(token,userNo,))
            timer.start()

if __name__ == "__main__":
    print("flask初始化...")
    server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
    server.serve_forever()